package com.android.json.load;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/*************************文件信息*****************************
 * 模块名：AnJia
 * 文件名：JsonPaser.java 
 * 创建者：刘松
 * 创建日期： 2015年2月6日 
 * 功能描述：
 ***********************************************************/
public class JsonPaser {

	static JsonPaser instance;

	static JsonPaser getInstance() {
		if (instance == null)
			instance = new JsonPaser();
		return instance;
	}

	Object parseJson2Object(String data, String className) throws JSONException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		JSONObject jsonObject = new JSONObject(data);
		Class<?> forName = Class.forName(className);
		Field[] fields = forName.getFields();
		for (Field field : fields) {
			String fieldName = field.getName();
			String value = jsonObject.getString(fieldName);
			field.set(fieldName, value);
		}
		 Object newInstance = forName.newInstance();
		return forName;
	}

	List<?> parseJson2Array(String data, String className) throws JSONException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		List array = new ArrayList<Object>();
		JSONObject jsonObject;

		JSONArray jsonArray = new JSONArray(data);
		int length = jsonArray.length();
		for (int i = 0; i < length; i++) {
			jsonObject = jsonArray.getJSONObject(i);
			Class<?> forName = Class.forName(className);
			Field[] fields = forName.getFields();
			for (Field field : fields) {
				String fieldName = field.getName();
				String value = jsonObject.getString(fieldName);
				field.set(fieldName, value);
			}
			array.add(forName);
		}

		// Object newInstance = forName.newInstance();
		return array;
	}

	String parseCode(String data) throws JSONException {
		JSONObject jsonObject = new JSONObject(data);
		String code = jsonObject.getString("code");
		if (code == null)
			code = jsonObject.getString("state");
		return code;
	}
}
